﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Xml.Linq;
using Android;
using Android.App;
using Android.OS;
using Android.Widget;

namespace SCPAK2
{
    [Activity(Label = "Guid去重器", Theme = "@style/AppTheme")]
    public class GuidRepeatAwayActivity : Activity
    {
        public ListView LogList;
        public TextView PathText;
        public Button MakeButton;
        public XElement Database;
        public SimpleTextAdapter TextAdapter;
        public Dictionary<string, XElement> Words = new Dictionary<string, XElement>();
        public Dictionary<string, XElement> Modify = new Dictionary<string, XElement>();
        public CheckBox fixGuid, clearGuid;
        public bool IsRun;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_guidrepeataway);
            LogList = (ListView)FindViewById(Resource.Id.logList);
            PathText = (TextView)FindViewById(Resource.Id.textView1);
            MakeButton = (Button)FindViewById(Resource.Id.button2);
            fixGuid = FindViewById<CheckBox>(Resource.Id.fixGuid);
            clearGuid = FindViewById<CheckBox>(Resource.Id.clearGuid);
            MakeButton.Click += new EventHandler(DoReplace);
            Bundle config = Intent.GetBundleExtra("file");
            string fullname = config.GetString("fullname");
            string name = config.GetString("name");
            PathText.Text = fullname;
            TextAdapter = new SimpleTextAdapter(this);
            LogList.Adapter = TextAdapter;
            if (CheckSelfPermission(Manifest.Permission.WriteExternalStorage) != Android.Content.PM.Permission.Granted)
            {
                RequestPermissions(new string[] { Manifest.Permission.WriteExternalStorage, Manifest.Permission.ReadExternalStorage }, 0);
            }
            new Thread(new ThreadStart(() =>
            {
                RunOnUiThread(() => { AppendLog("解析Database中"); });
                using (Stream stream = Assets.Open("Database.xml"))
                {
                    Database = XElement.Load(stream, LoadOptions.None);
                }
                RunOnUiThread(() => { AppendLog("Database解析完成"); });
            })).Start();
        }
        public void AppendLog(string text)
        {
            TextAdapter.Add(text);
            TextAdapter.NotifyDataSetChanged();
        }
        public void DoReplace(object obj, EventArgs args)
        {
            if (Database == null)
            {
                Tip("Database解析失败，不能执行任务");
            }
            else
            {
                new Thread(new ThreadStart(() =>
                {
                    if (IsRun) { RunOnUiThread(() => { Tip("请等待当前任务完成"); }); return; }
                    IsRun = true;
                    RunOnUiThread(() => { AppendLog("正在执行中"); });
                    Modify.Clear();
                    Words.Clear();
                    using (Stream stream = File.OpenRead(PathText.Text))
                    {
                        XElement xElement = XElement.Load(stream, LoadOptions.None);
                        LoadAllElement1(Database);
                        LoadAllElement1(xElement, true);
                        LoadAllElement2(xElement);
                        string txt = xElement.ToString();
                        using (Stream stream1 = File.Create(PathText.Text + ".xdb"))
                        {
                            xElement.Save(stream1);
                        }
                        RunOnUiThread(() => { AppendLog("已保存新文件到" + PathText.Text + ".xdb"); });
                    }
                    IsRun = false;
                })).Start();
            }
        }
        //修改重复的Guid，并把所有元素加入到Guid列表与修改过的列表
        public void LoadAllElement1(XElement xElement, bool AllowClear = false)
        {
            foreach (XElement element in xElement.Elements())
            {
                XAttribute attribute = element.Attribute("Guid");
                if (attribute != null)
                {
                    if (element.Name == "ComponentTemplate" || element.Name == "MemberComponentTemplate" || element.Name == "EntityTemplate" || element.Name == "ProjectTemplate")
                    { //重复了，重置该元素的Guid，并加入到修改列表
                        if (AllowClear && fixGuid.Checked)
                        {
                            try { Guid guid = new Guid(attribute.Value); }
                            catch(Exception e)
                            {
                                string v = attribute.Value;
                                attribute.Value = Guid.NewGuid().ToString();
                                if(Modify.ContainsKey(v)==false)Modify.Add(v, element);
                                RunOnUiThread(() =>
                                {
                                    AppendLog("修正Guid " + v + "为" + attribute.Value + "在" + element.Name);
                                });
                            }
                        }
                        if (Words.TryGetValue(attribute.Value, out XElement ele))
                        {
                            RunOnUiThread(() =>
                            {
                                AppendLog("检测到重复Guid" + attribute.Value + "在" + element.Name);
                            });
                            string guid = Guid.NewGuid().ToString();
                            if (Modify.ContainsKey(attribute.Value) == false) Modify.Add(attribute.Value, ele);
                            ele.SetAttributeValue("Guid", guid);
                        }
                        else
                        {
                            Words.Add(attribute.Value, element);
                        }
                    }else if (AllowClear && clearGuid.Checked && element.Name.ToString().StartsWith("Parameter") && attribute != null)
                    {
                        attribute.Remove();
                        RunOnUiThread(() =>
                        {
                            AppendLog("精简" + attribute);
                        });
                    }
                }
                LoadAllElement1(element, AllowClear);
            }
        }
        //修改继承Guid
        public void LoadAllElement2(XElement xElement)
        {
            foreach (XElement element in xElement.Elements())
            {
                XAttribute attribute = element.Attribute("InheritanceParent");
                if (attribute != null)
                { //有继承Guid，在修改的列表里面查找有没有变动的，找到了就重置该guid
                    string inheritGuid = attribute.Value;
                    if (Modify.TryGetValue(inheritGuid, out XElement ele))
                    {
                        RunOnUiThread(() =>
                        {
                            AppendLog("重置继承Guid" + attribute.Value + "在" + element.Name);
                        });
                        element.SetAttributeValue("InheritanceParent", ele.Attribute("Guid").Value);
                    }
                }
                LoadAllElement2(element);
            }
        }
        public void Tip(string msg)
        {
            Toast.MakeText(this, msg, ToastLength.Long).Show();
        }
    }
}